import { isArray, isEmpty, isString } from 'lodash';
import ErrorTips from './ErrorTips';
import NativeSelect from './NativeSelect';

const UNIT_JSON = {
  time: ['s', 'h'],
  length: ['mm', 'cm', 'm'],
  area: ['mm^2', 'cm^2', 'dm^2', 'm^2'],
  volume: ['m^3', 'dm^3', 'cm^3', 'mm^3'],
  speed: ['m/s', 'km/h'],
  acceleration: ['mm/s^2', 'm/s^2', 'km/h^2'],
  angle: ['rad', '°'],
  angularSpeed: ['rad/s', '°/s'],
  mass: ['g', 'kg'],
  pressure: ['Pa', 'kPa', 'MPa'],
  force: ['N', 'kN'],
  torque: ['N*mm', 'N*cm', 'N*m'],
  density: ['g/mm^3', 'g/cm^3', 'kg/m^3'],
  temperature: ['C', 'K'],
};
/**
 * 判断是否是合法的Unit，Unit必须是string或string[]
 * @param {unknown} unit
 * @return {boolean} 是否合法
 */
const isValidUnit = (unit: unknown) => {
  return (
    (isString(unit) && Object.keys(UNIT_JSON).includes(unit)) ||
    (isArray(unit) &&
      !isEmpty(unit) &&
      unit.every((u) => isString(u) && !isEmpty(u)))
  );
};
export default function UnitSelect({
  units,
  value,
  disabled,
  onChange,
}: {
  units: unknown;
  value?: string;
  disabled?: boolean;
  onChange?: (value: string) => void;
}) {
  if (units === undefined) return <></>;
  if (isValidUnit(units)) {
    let units1 = [];
    if (isString(units)) {
      // 从UNIT_JSON中获取对应的Unit
      units1 = UNIT_JSON[units] ?? [];
    } else if (isArray(units)) {
      units1 = units;
    }
    const unitOptions = units1.map((u) => ({ value: u, label: u }));
    return (
      <NativeSelect
        options={unitOptions}
        value={value ?? ''}
        disabled={disabled}
        onChange={(value) => {
          onChange?.(value as string);
        }}
      />
    );
  } else {
    return (
      <ErrorTips>{`格式错误，无效的Unit：${JSON.stringify(units)}`}</ErrorTips>
    );
  }
}
